package com.sailorj.service.impl;

import com.sailorj.entity.SysUser;
import com.sailorj.mapper.SysUserMapper;
import com.sailorj.service.SysUserService;
import com.sailorj.util.GsonUtil;
import com.sailorj.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component//异步调用设置
@Service
public class SysUserServiceImpl implements SysUserService {

    public String result = "";

    @Autowired
    public SysUserMapper userMapper;

    public SysUser login(SysUser user){
       return userMapper.login(user);
    }

    @Override
    public SysUser findByUserName(String name) {
        return userMapper.findUserNameByName(name);
    }

    @Override
    @Async//异步调用设置
    @Transactional(propagation = Propagation.REQUIRED)//事务回滚，发生错误不执行插入操作
    public String addUser(SysUser user) {
        SysUser existUser=userMapper.findUserNameByName(user.getUserName());
        System.out.println(" -- > 用户名是否存在=" + GsonUtil.GsonString(existUser));
        try
        {
            if (existUser !=null){
                result=" -- > 用户名已存在！";
                System.out.println(" -- > 用户名已存在！");
            }
            else {
                userMapper.insert(user);
                result=" -- > 注册成功！";
                System.out.println(" -- > 注册成功！");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    @Override
    @Async
    @Transactional(propagation = Propagation.REQUIRED)//事务回滚，发生错误不执行插入操作
    public void delUserById(int id) {
         userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Async
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUserById(SysUser user) {
          userMapper.updateByPrimaryKey(user);
    }

    //不能用异步
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public SysUser getUserById(int id) {
        System.out.println("getUserById -- > " + id);
        return userMapper.selectByPrimaryKey(id);
    }


    //不能用异步
//    @Transactional(propagation = Propagation.REQUIRED)
//    public List<SysUser> getUserList() {
//        return userMapper.selectUserList();
//    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED)//事务回滚，发生错误不执行插入操作
    public PageBean getUserList(Integer page, Integer size) {
        if(page!=null&&size!=null){
            page=(page-1)*size;
        }
        List<SysUser> data = userMapper.selectUserList(page,size);
        Long total=userMapper.getTotal();
        PageBean bean = new PageBean();
        bean.setData(data);
        bean.setTotal(total);
        return bean;
    }
}
